package owg.util.awt;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JCheckBox;

public class BooleanEditor extends TypeEditor<Boolean> implements ActionListener
	{
	static final long serialVersionUID = 2704835030524222876L;
	
	JCheckBox box;
	boolean value;
	boolean ignoreEvents = false;
	Color origcolor;
	
	public BooleanEditor(boolean initialValue)
		{
		super(Boolean.class);
		
		box = new JCheckBox();
		origcolor = box.getBackground();
		setValue(initialValue, false);
		add(box);
		box.addActionListener(this);
		}

	private void setValue(boolean val, boolean fire)
		{
		boolean pVal = value;
		value = val;
		ignoreEvents = true;
		box.setSelected(val);
		ignoreEvents = false;
		if(fire && pVal != value)
			{
			fireActionEvents();
			flash(Color.GREEN);
			}
		}
	@Override
	public void actionPerformed(ActionEvent e)
		{
		if(!ignoreEvents)
			parseValue();
		}

	private void parseValue()
		{
		try {
			setValue(box.isSelected(), true);
			}
		catch(NumberFormatException e)
			{
			flash(Color.RED);
			setValue(value);
			}
		}

	synchronized void color(Color color)
		{
		box.setBackground(color);
		}

	private void flash(Color color)
		{
		color(color);
		flashThread(new Runnable(){public void run(){color(origcolor);}}, 33);
		}

	@Override
	public Boolean getValue()
		{
		return value;
		}

	@Override
	public void setValue(Boolean val)
		{
		setValue(val, false);
		}

	@Override
	public void setToolTipTextToSubComponents(String text)
		{
		box.setToolTipText(text);
		}

	@Override
	public void setSubComponentsEnabled(boolean en)
		{
		box.setEnabled(en);
		}
	}
